package br.ufpe.cin.rdfilter.gui;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.GroupLayout.Alignment;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.RDFNode;

import br.ufpe.cin.rdfilter.feedback.Annotation;
import br.ufpe.cin.rdfilter.feedback.Feedback;
import br.ufpe.cin.rdfilter.feedback.Triple;
import br.ufpe.cin.rdfilter.relevance.Relevance;
import br.ufpe.cin.rdfilter.util.FeedbackInference;
import br.ufpe.cin.rdfilter.util.LoadFeedback;
import br.ufpe.cin.rdfilter.util.LoadQuery;

/**
 * 
 * @author Rafael
 */
public class FrameTool extends javax.swing.JFrame {
	private javax.swing.JButton btnEditLine;
	private javax.swing.JButton btnFeedback;
	private javax.swing.JButton btnSubmit;
	private javax.swing.JButton btnQuery;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JPopupMenu.Separator jSeparator1;
	private javax.swing.JMenu menuFile;
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JMenu menuTool;
	private javax.swing.JMenuItem menuItemOpenQuery;
	private javax.swing.JMenuItem menuItemOpenResult;
	private javax.swing.JMenu menuRelevance;
	private JMenuItem menuItemCalculate;
	private javax.swing.JMenu menuItemHelp;
	private javax.swing.JMenuItem menuItemEstatistics;
	private javax.swing.JMenuItem menuItemClose;
	private javax.swing.JMenuItem menuAbout;
	private javax.swing.JTable tableResult;
	private javax.swing.JTextArea textAreaQuery;
	TitledBorder titleBorderQuery = javax.swing.BorderFactory
			.createTitledBorder("Query");
	TitledBorder titleBorderResult = javax.swing.BorderFactory
			.createTitledBorder("Result");

	private static final long serialVersionUID = 1L;

	private String idQuery = "";
	private String idResult = "";
	private Triple[] resultTriple = null;
	private List<Annotation> annotatedTriple = new ArrayList<Annotation>();
	DefaultTableModel tableModel;
	File fileFeedback;
	
	public FrameTool() {
		initComponents();
		this.setTitle("RDF Fan");
		tableResult.setFillsViewportHeight(true);
		tableResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableResult.setCellSelectionEnabled(true);
		buttonsEnabled(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */

	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {
		jPanel1 = new javax.swing.JPanel();
		jScrollPane1 = new javax.swing.JScrollPane();
		textAreaQuery = new javax.swing.JTextArea();
		jPanel2 = new javax.swing.JPanel();
		jScrollPane2 = new javax.swing.JScrollPane();
		tableResult = new javax.swing.JTable();
		jPanel3 = new javax.swing.JPanel();
		btnEditLine = new javax.swing.JButton();
		btnFeedback = new javax.swing.JButton();
		btnSubmit = new javax.swing.JButton();
		btnQuery = new javax.swing.JButton();
		menuBar = new javax.swing.JMenuBar();
		menuFile = new javax.swing.JMenu();
		menuItemOpenQuery = new javax.swing.JMenuItem();
		menuItemOpenResult = new javax.swing.JMenuItem();
		jSeparator1 = new javax.swing.JPopupMenu.Separator();
		menuItemClose = new javax.swing.JMenuItem();
		menuTool = new javax.swing.JMenu();
		menuItemEstatistics = new javax.swing.JMenuItem();
		menuItemHelp = new javax.swing.JMenu();
		menuAbout = new javax.swing.JMenuItem();
		menuRelevance = new JMenu();
		menuItemCalculate = new JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		jPanel1.setBorder(titleBorderQuery);
		textAreaQuery.setColumns(20);
		textAreaQuery.setEditable(true);
		textAreaQuery.setRows(5);
		jScrollPane1.setViewportView(textAreaQuery);
		btnQuery.setText("Query");
		btnQuery.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
        	btnQueryActionPerformed(evt);
        }
        });
		
		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(Alignment.TRAILING,jPanel1Layout.createSequentialGroup()
				.addComponent(
				jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 710,
				Short.MAX_VALUE).addComponent(btnQuery)));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(Alignment.TRAILING,jPanel1Layout.createSequentialGroup()
				.addComponent(
				jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 184,
				Short.MAX_VALUE).addComponent(btnQuery)));
		jPanel2.setBorder(titleBorderResult);
		tableModel = new javax.swing.table.DefaultTableModel(new Object[][] {},
				new String[] { "Subject", "Predicate", "Object" }) {
			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		tableResult.setModel(tableModel);
		jScrollPane2.setViewportView(tableResult);
		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(
				jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 567,
				Short.MAX_VALUE));
		jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel2Layout
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane2,
								javax.swing.GroupLayout.DEFAULT_SIZE, 215,
								Short.MAX_VALUE)));
		jPanel3.setBorder(javax.swing.BorderFactory
				.createTitledBorder("Feedback"));
		btnEditLine.setText("Edit line");
		btnEditLine.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnEditLineActionPerformed(evt);
			}
		});
		btnFeedback.setText("Annotation");
		btnFeedback.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnFeedbackActionPerformed(evt);
			}
		});
		btnSubmit.setFont(new java.awt.Font("Tahoma", 1, 11));
		btnSubmit.setText("Submit");
		btnSubmit.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnSubmitActionPerformed(evt);
			}
		});
		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(
				jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout
				.setHorizontalGroup(jPanel3Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel3Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																btnSubmit,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																105,
																Short.MAX_VALUE)
														.addComponent(
																btnFeedback,
																javax.swing.GroupLayout.Alignment.TRAILING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																105,
																Short.MAX_VALUE)
														.addComponent(
																btnEditLine,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																105,
																Short.MAX_VALUE))
										.addContainerGap()));
		jPanel3Layout
				.setVerticalGroup(jPanel3Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel3Layout
										.createSequentialGroup()
										.addGap(50, 50, 50)
										.addComponent(
												btnEditLine,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												31,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(
												btnFeedback,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												31,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												53, Short.MAX_VALUE)
										.addComponent(
												btnSubmit,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												32,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));
		menuFile.setText("File");
		menuItemOpenQuery.setText("Open Query");
		menuItemOpenQuery
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						menuItemOpenQueryActionPerformed(evt);
					}
				});
		menuFile.add(menuItemOpenQuery);
		menuItemOpenResult.setText("Open Result");
		menuItemOpenResult
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						menuItemOpenResultActionPerformed(evt);
					}
				});
		menuFile.add(menuItemOpenResult);
		menuFile.add(jSeparator1);
		menuItemClose.setText("Close");
		menuItemClose.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				menuItemCloseActionPerformed(evt);
			}
		});
		menuFile.add(menuItemClose);
		menuBar.add(menuFile);
		menuTool.setText("Tool");
		menuItemEstatistics.setText("Estatistics");
		menuItemEstatistics
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						menuItemEstatisticsActionPerformed(evt);
					}
				});
		menuTool.add(menuItemEstatistics);
		menuBar.add(menuTool);
		menuRelevance.setText("Relevance");
		menuItemCalculate.setText("Calculate");
		menuItemCalculate
		.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				menuItemCalculateActionPerformed(evt);
			}
		});
		menuRelevance.add(menuItemCalculate);
		menuBar.add(menuRelevance);
		menuItemHelp.setText("Help");
		menuAbout.setText("About");
		menuAbout.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				menuAboutActionPerformed(evt);
			}
		});
		menuItemHelp.add(menuAbout);
		menuBar.add(menuItemHelp);
		setJMenuBar(menuBar);
		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(
														jPanel1,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addGroup(
														javax.swing.GroupLayout.Alignment.TRAILING,
														layout.createSequentialGroup()
																.addComponent(
																		jPanel2,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		Short.MAX_VALUE)
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																.addComponent(
																		jPanel3,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.PREFERRED_SIZE)))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jPanel1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(
														jPanel3,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addComponent(
														jPanel2,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE))
								.addContainerGap()));

		pack();
	}// </editor-fold>

	private void btnQueryActionPerformed(ActionEvent evt){
//		LoadFeedback f = new LoadFeedback(new File("feedback.xml"));
//		f.load("Consulta1","teste2");
		String endpoint = "http://api.talis.com/stores/bbc-backstage/services/sparql";						
		
		String query = "PREFIX owl: <http://www.w3.org/2002/07/owl#> "+
					   "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "+
					   "PREFIX purl-owl: <http://purl.org/ontology/mo/> "+
					   "PREFIX purl-vocab: <http://purl.org/vocab/relationship/> "+
					
					   "SELECT ?memberName ?predicate ?memberPage WHERE{ "+
					   " { <http://www.bbc.co.uk/music/artists/b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d#artist> purl-owl:member ?member . } "+
					   " { ?member foaf:name ?memberName . } "+
					   " { ?member ?predicate ?memberPage. } "+
					  
					   " FILTER (?predicate = foaf:page) "+
					   "}";
		
		QueryExecution queryExecution = QueryExecutionFactory.sparqlService(endpoint, query);
		ResultSet results = queryExecution.execSelect();
		
		while(results.hasNext()){
			
			QuerySolution result = results.next();
			
			Iterator<String> varNames = result.varNames();
			
			RDFNode answerField;
			
			while(varNames.hasNext()){
				answerField = result.get(varNames.next());
				
				System.out.print(answerField +" | ");
			}
			
			System.out.print("\n");
		}
	}
	
	private void btnEditLineActionPerformed(java.awt.event.ActionEvent evt) {
		int selectedIndex = tableResult.getSelectedRow();
		if (selectedIndex != -1 && selectedIndex < tableModel.getRowCount()) {
			Triple triplaSelected = resultTriple[selectedIndex];
			FrameAddEdit editFrame = new FrameAddEdit(
					triplaSelected, this, false, "Edit result", null);
			editFrame.setVisible(true);
		} else
			JOptionPane.showMessageDialog(null,
					"Select one line of the table");
	}

	private void btnFeedbackActionPerformed(java.awt.event.ActionEvent evt) {
		FrameAnnotation frameAnnotation = new FrameAnnotation(annotatedTriple, this);
		frameAnnotation.setVisible(true);
	}

	private void menuItemOpenQueryActionPerformed(
			java.awt.event.ActionEvent evt) {
		if (annotatedTriple.size() == 0) {
			JFileChooser fc = new JFileChooser();
			fc.setDialogTitle("Load Query");
			int response = fc.showOpenDialog(null);
			if (response == JFileChooser.APPROVE_OPTION) {
				textAreaQuery.setText("");
				try {
					File dir = fc.getSelectedFile();
					String[] name = dir.getName().split("\\.");
					setIdQuery(name[0]);
					if (name[1].equals("txt")) {
						FileReader fr = new FileReader(dir);
						BufferedReader bufRdr = new BufferedReader(fr);
						String line = null;
						while ((line = bufRdr.readLine()) != null) {
							textAreaQuery.append(line);
							textAreaQuery.append("\n");
						}
						bufRdr.close();
						if (tableModel != null && tableModel.getRowCount() > 0) {
							buttonsEnabled(true);
						}
					}
					else
						JOptionPane.showMessageDialog(null,
								"Select a file with extension .txt");
				} catch (IOException ioex) {
					System.err.println(ioex);
					System.exit(1);
				}
			}
		} else {
			JOptionPane
					.showMessageDialog(null,
							"Click the Submit button before to load a new query");
		}
	}

	private void menuItemOpenResultActionPerformed(
			java.awt.event.ActionEvent evt) {
		if (annotatedTriple.size() == 0) {
			JFileChooser fc = new JFileChooser();
			fc.setDialogTitle("Load Result");
			int response = fc.showOpenDialog(null);
			if (response == JFileChooser.APPROVE_OPTION) {
				try {
					File dir = fc.getSelectedFile();
					String[] name = dir.getName().split("\\.");
					setIdResult(name[0]);
					if (name[1].equals("xml")) {
						javax.swing.table.DefaultTableModel dtm = (javax.swing.table.DefaultTableModel) tableResult
								.getModel();
						dtm.getDataVector().removeAllElements();
						try {
							DocumentBuilderFactory dbf = DocumentBuilderFactory
									.newInstance();
							DocumentBuilder db;
							db = dbf.newDocumentBuilder();
							Document doc;
							doc = db.parse(dir);
							Element root = doc.getDocumentElement();
							NodeList headList = root
									.getElementsByTagName("head");
							Element head = (Element) headList.item(0);
							NodeList varList = head
									.getElementsByTagName("variable");
							for (int i = 0; i < varList.getLength(); i++) {
								Element variableE = (Element) varList
										.item(i);
								Attr nameVar = variableE
										.getAttributeNode("name");
							}
							Element result = (Element) root.getElementsByTagName("results").item(0);
							NodeList resultList = result.getElementsByTagName("result");
							resultTriple = new Triple[resultList.getLength()];
							for (int i = 0; i < resultList.getLength(); i++) {
								Element resultE = (Element) resultList
										.item(i);
								Triple triple = createTriple(resultE);
								resultTriple[i] = triple;
							}
							for (int i = 0; i < resultTriple.length; i++) {
								dtm.addRow(new Object[] {
										resultTriple[i].getSubject(),
										resultTriple[i].getPredicate(),
										resultTriple[i].getObject() });
							}
							if (!textAreaQuery.getText().equals("")) {
								buttonsEnabled(true);
							}
						} catch (ParserConfigurationException e) {
							e.printStackTrace();
						} catch (SAXException e) {
							e.printStackTrace();
						}
					}
					else
						JOptionPane.showMessageDialog(null,
								"Select a file with extension .xml");
				} catch (IOException ioex) {
					System.err.println(ioex);
					System.exit(1);
				}
			}
		} else {
			JOptionPane
					.showMessageDialog(null,
							"Click the Submit button before to load a new query");
		}
	}
	
	private void menuItemCalculateActionPerformed(ActionEvent evt) {
		
		LoadFeedback f = new LoadFeedback(new File ("feedback.xml"));
		List<Feedback> feedback = f.loadFeedback();
		ArrayList<Double> weight = new ArrayList<Double>();
		for(int i=0;i<feedback.size();i++){
			weight.add(1.0);
		}
		LoadQuery query = new LoadQuery(new File("ConsultasResultados/query3-2.xml"));
		query.load();
		ArrayList<Triple> list = query.getArrayTriple();
		FeedbackInference fi =null;
		List<Feedback> f_infered = new ArrayList<Feedback>();
		for(int i=0;i<feedback.size();i++){
			fi = new FeedbackInference(feedback.get(i).getAnnotation(), list);
			f_infered.add(fi.setInference2());
		}
		Relevance r = new Relevance(feedback,f_infered,weight);
		System.out.println("Feedback before:");
		System.out.println("TP: "+feedback.get(0).getTp());
		System.out.println("FP: "+feedback.get(0).getFp());
		System.out.println("FN: "+feedback.get(0).getFn());
		System.out.println("Precision: "+feedback.get(0).getPrecision());
		System.out.println("Recall: "+feedback.get(0).getRecall());
		System.out.println("F-Measure: "+feedback.get(0).getF_measure());
		System.out.println("Feedback after: ");
		System.out.println("TP: "+f_infered.get(0).getTp());
		System.out.println("FP: "+f_infered.get(0).getFp());
		System.out.println("FN: "+f_infered.get(0).getFn());
		System.out.println("Precision: "+f_infered.get(0).getPrecision());
		System.out.println("Recall: "+f_infered.get(0).getRecall());
		System.out.println("F-Measure: "+f_infered.get(0).getF_measure());
		
		System.out.println("Benefit: "+r.getBenefit());
		System.out.println("Relevance: "+r.getRelevance());
	}
	
	private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			FileWriter writer = new FileWriter("saida.txt",true);
			PrintWriter out = new PrintWriter(writer,true);
			
			for(Annotation annotation : annotatedTriple){
				out.println(annotation.getIdQuery() + ";"
						+ annotation.getTriple().getSubject() + ";"
						+ annotation.getTriple().getPredicate() + ";"
						+ annotation.getTriple().getObject() + ";"
						+ annotation.getType() + ";"
						+ annotation.getConfidence());
			}			
			out.close();
			writer.close();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		/**
		try {
		
			
			Document doc;
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Element rootElement;
			fileFeedback = new File("feedback.xml");
			if (fileFeedback.exists()) {
				doc = docBuilder.parse(fileFeedback);
				rootElement = doc.getDocumentElement();
				NodeList queryList = rootElement
						.getElementsByTagName("query");
				boolean existQuery = false;
				for (int index = 0; index < annotatedTriple.size(); index++) {
					for (int j = 0; j < queryList.getLength(); j++) {
						Element queryE = (Element) queryList.item(j);
						String idQuery = queryE.getAttributeNode("id").getValue();
						if (annotatedTriple.get(index).getIdQuery()
								.equals(idQuery)) {
							existQuery = true;
							NodeList feedbackList = queryE
									.getElementsByTagName("feedback");
							boolean sameFeedback = false;
							for (int m = 0; m < feedbackList.getLength(); m++) {
								Element feedback = (Element) feedbackList
										.item(m);
								String idFeedback = feedback.getAttributeNode("id").getValue();
								if (annotatedTriple.get(index).getIdResult().equals(idFeedback)) {
									sameFeedback = true;
									newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
									break;
								}
							}
							if (!sameFeedback) {
								Element feedback = doc
										.createElement("feedback");
								Attr attrIdResult = doc.createAttribute("id");
								attrIdResult.setValue(annotatedTriple.get(index).getIdResult());
								feedback.setAttributeNode(attrIdResult);
								queryE.appendChild(feedback);
								newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
							}
							break;
						}
					}
					if (!existQuery) {
						Element query = doc.createElement("query");
						rootElement.appendChild(query);
						Attr attrIdQuery = doc.createAttribute("id");
						attrIdQuery.setValue(annotatedTriple.get(index)
								.getIdQuery());
						query.setAttributeNode(attrIdQuery);
						rootElement.appendChild(query);
						Element feedback = doc.createElement("feedback");
						Attr attrIdResult = doc.createAttribute("id");
						attrIdResult.setValue(annotatedTriple.get(index)
								.getIdResult());
						feedback.setAttributeNode(attrIdResult);
						query.appendChild(feedback);
						newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
					}
					existQuery = false;
				}
			}
			else {
				doc = docBuilder.newDocument();
				rootElement = doc.createElement("queries");
				doc.appendChild(rootElement);
				NodeList queryList = rootElement.getElementsByTagName("query");
				boolean existQuery = false;
				for (int index = 0; index < annotatedTriple.size(); index++) {
					for (int j = 0; j < queryList.getLength(); j++) {
						Element query = (Element) queryList.item(j);
						String idQuery = query.getAttributeNode("id").getValue();
						if (annotatedTriple.get(index).getIdQuery().equals(idQuery)) {
							existQuery = true;
							NodeList feedbackList = query
									.getElementsByTagName("feedback");
							boolean sameFeedback = false;
							for (int m = 0; m < feedbackList.getLength(); m++) {
								Element feedback = (Element) feedbackList
										.item(m);
								String idFeedback = feedback.getAttributeNode("id").getValue();
								if (annotatedTriple.get(index).getIdResult()
										.equals(idFeedback)) {
									sameFeedback = true;
									newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
									break;
								}
							}
							if (!sameFeedback) {
								Element feedback = doc
										.createElement("feedback");
								Attr attrIdResult = doc
										.createAttribute("id");
								attrIdResult.setValue(annotatedTriple.get(
										index).getIdResult());
								feedback.setAttributeNode(attrIdResult);
								query.appendChild(feedback);
								newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
							}
							break;
						}
					}
					if (!existQuery) {
						Element query = doc.createElement("query");
						rootElement.appendChild(query);
						Attr attrIdQuery = doc.createAttribute("id");
						attrIdQuery.setValue(annotatedTriple.get(index)
								.getIdQuery());
						query.setAttributeNode(attrIdQuery);
						rootElement.appendChild(query);
						Element feedback = doc.createElement("feedback");
						Attr attrIdResult = doc.createAttribute("id");
						attrIdResult.setValue(annotatedTriple.get(index)
								.getIdResult());
						feedback.setAttributeNode(attrIdResult);
						query.appendChild(feedback);
						newXMLAnnotation(doc, feedback,annotatedTriple.get(index));
					}
					existQuery = false;
				}
			}
			if (annotatedTriple.size() != 0) {
				TransformerFactory transformerFactory = TransformerFactory
						.newInstance();
				Transformer transformer;
				transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
				StreamResult result = new StreamResult(fileFeedback);
				transformer.transform(source, result);
				String lines = "";
				if (annotatedTriple.size() > 1) {
					lines = annotatedTriple.size() + " lines were annotated.";
				} else {
					lines = "1 line was annotated.";
				}
				JOptionPane
						.showMessageDialog(
								null,
								"Feedback submitted with success!\n"
										+ lines
										+ "\nThe annotation list has no more records.");
				annotatedTriple.clear();
			}
			else {
				JOptionPane.showMessageDialog(null,
						"No triple was annotated.");
			}
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		*/
	}

	public Triple createTriple(Element element) {
		Triple triple = new Triple();
		NodeList bindList = element.getElementsByTagName("binding");
		
		Element bindS = (Element) bindList.item(0);
		NodeList uriSList = bindS.getElementsByTagName("uri");
		Node noS = ((Element) uriSList.item(0)).getFirstChild();
		triple.setSubject(noS.getNodeValue());

		Element bindP = (Element) bindList.item(1);
		NodeList uriPList = bindP.getElementsByTagName("uri");
		Node noP = ((Element) uriPList.item(0)).getFirstChild();
		triple.setPredicate(noP.getNodeValue());

		Element bindO = (Element) bindList.item(2);
		NodeList literalList = bindO.getElementsByTagName("literal");
		Node noO = ((Element) literalList.item(0)).getFirstChild();
		triple.setObject(noO.getNodeValue());

		return triple;
	}

	private void newXMLAnnotation(Document doc, Element feedback,
			Annotation annotatedTriple) {
		Element annotation = doc.createElement("annotation");
		feedback.appendChild(annotation);

		Element triple = doc.createElement("triple");
		annotation.appendChild(triple);

		Element subject = doc.createElement("subject");
		subject.appendChild(doc.createTextNode(annotatedTriple.getTriple()
				.getSubject()));
		triple.appendChild(subject);

		Element predicate = doc.createElement("predicate");
		predicate.appendChild(doc.createTextNode(annotatedTriple.getTriple()
				.getPredicate()));
		triple.appendChild(predicate);

		Element object = doc.createElement("object");
		object.appendChild(doc.createTextNode(annotatedTriple.getTriple()
				.getObject()));
		triple.appendChild(object);

		Element idQuery = doc.createElement("idQuery");
		idQuery.appendChild(doc.createTextNode(annotatedTriple.getIdQuery()));
		annotation.appendChild(idQuery);

		Element evaluation = doc.createElement("evaluation");
		evaluation.appendChild(doc.createTextNode(annotatedTriple.getType()));
		annotation.appendChild(evaluation);

		Element confidence = doc.createElement("confidence");
		confidence.appendChild(doc.createTextNode(annotatedTriple.getConfidence()));
		annotation.appendChild(confidence);
	}

	private void buttonsEnabled(boolean val) {
		btnEditLine.setEnabled(val);
		btnFeedback.setEnabled(val);
		btnSubmit.setEnabled(val);
	}

	private void menuItemCloseActionPerformed(java.awt.event.ActionEvent evt) {
		dispose();
	}

	private void menuItemEstatisticsActionPerformed(
			java.awt.event.ActionEvent evt) {
		FrameStatistics frameEstatistic = new FrameStatistics();
		frameEstatistic.setVisible(true);
	}

	private void menuAboutActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	public List<Annotation> getAnnotatedTriple() {
		return annotatedTriple;
	}

	public void setAnnotatedTriple(List<Annotation> annotatedTriple) {
		this.annotatedTriple = annotatedTriple;
	}

	public void addAnnotatedTriple(Annotation annotation) {
		this.annotatedTriple.add(annotation);
	}

	public String getIdResult() {
		return idResult;
	}

	public void setIdResult(String idResult) {
		this.idResult = idResult;
	}

	public String getIdQuery() {
		return idQuery;
	}

	public void setIdQuery(String idQuery) {
		this.idQuery = idQuery;
	}
}